import {
	addTopic,
	deleteTopic,
	editTopic,
	queryTopicPage,
	type ITopicInfoResponse,
	type ITopicListParams
} from '@/api/myResearch';
import { useRequest } from '@ac/hooks';
import { AppPagination, EmptyState } from '@ac/ui-components';
import { DeleteOutlined, EditOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, Card, Modal, message } from 'antd';
import to from 'await-to-js';
import { useCallback, useEffect, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { useImmer } from 'use-immer';
import CreateTopicModal from '../Dialog/CreateTopicDialog';

// ==================== 类型定义 ====================

/**
 * 选题卡片组件属性接口
 */
interface TopicCardProps {
	topic: ITopicInfoResponse;
	onEdit: (topic: ITopicInfoResponse) => void;
	onDelete: (id: string) => void;
}

/**
 * 弹窗表单数据接口
 */
interface TopicFormData {
	name: string;
	tags: string;
}

/**
 * 组件状态接口
 */
interface ResearchTopicsState {
	isModalVisible: boolean;
	currentEditTopic: ITopicInfoResponse | null;
	topicList: ITopicInfoResponse[];
	total: number;
	pagination: ITopicListParams;
}

// ==================== 自定义 Hooks ====================

/**
 * 选题数据管理 Hook
 * 封装选题的增删改查逻辑
 */
const useTopicManagement = () => {
	const [state, setState] = useImmer<ResearchTopicsState>({
		isModalVisible: false,
		currentEditTopic: null,
		topicList: [],
		total: 0,
		pagination: {
			pageNum: 1,
			pageSize: 10
		}
	});

	/**
	 * 查询选题列表
	 */
	const { loading, run: fetchTopicList } = useRequest(
		useCallback(
			async (params: ITopicListParams) => {
				const [_error, response] = await to(queryTopicPage(params));

				if (response) {
					setState(state => {
						state.topicList = response.result || [];
						state.total = response.pageinfo?.pagecount || 0;
					});
				}
			},
			[setState]
		)
	);

	/**
	 * 删除选题
	 * @param id - 选题ID
	 */
	const handleDeleteTopic = useCallback(
		async (id: string) => {
			const [_err, res] = await to(deleteTopic({ id }));

			if (res) {
				message.success('删除成功');
				fetchTopicList(state.pagination);
			}
		},
		[state.pagination, fetchTopicList]
	);

	/**
	 * 保存选题（新增或编辑）
	 * @param values - 表单数据
	 */
	const handleSaveTopic = useCallback(
		async (values: TopicFormData) => {
			const isEdit = !!state.currentEditTopic?.id;
			const apiCall = isEdit
				? editTopic({ ...values, id: state.currentEditTopic!.id })
				: addTopic(values);

			const [_err, res] = await to(apiCall);

			if (res) {
				message.success(isEdit ? '编辑成功' : '添加成功');
				fetchTopicList(state.pagination);

				setState(state => {
					state.isModalVisible = false;
					state.currentEditTopic = null;
				});
			}
		},
		[state.currentEditTopic, state.pagination, fetchTopicList, setState]
	);

	/**
	 * 打开编辑弹窗
	 * @param topic - 要编辑的选题
	 */
	const handleEditTopic = useCallback(
		(topic: ITopicInfoResponse) => {
			setState(state => {
				state.isModalVisible = true;
				state.currentEditTopic = topic;
			});
		},
		[setState]
	);

	/**
	 * 打开新增弹窗
	 */
	const handleAddTopic = useCallback(() => {
		setState(state => {
			state.isModalVisible = true;
			state.currentEditTopic = null;
		});
	}, [setState]);

	/**
	 * 关闭弹窗
	 */
	const handleCloseModal = useCallback(() => {
		setState(state => {
			state.isModalVisible = false;
			state.currentEditTopic = null;
		});
	}, [setState]);

	/**
	 * 分页变化处理
	 * @param pageNum - 页码
	 * @param pageSize - 每页大小
	 */
	const handlePaginationChange = useCallback(
		(pageNum: number, pageSize: number) => {
			setState(state => {
				state.pagination = { pageNum, pageSize };
			});
		},
		[setState]
	);

	// 监听分页变化，自动获取数据
	useEffect(() => {
		fetchTopicList(state.pagination);
	}, [state.pagination, fetchTopicList]);

	return {
		state,
		loading,
		actions: {
			handleDeleteTopic,
			handleSaveTopic,
			handleEditTopic,
			handleAddTopic,
			handleCloseModal,
			handlePaginationChange
		}
	};
};

// ==================== 子组件 ====================

/**
 * 研究选题卡片组件
 * 展示单个选题信息，提供编辑和删除操作
 * @param topic - 选题数据
 * @param onEdit - 编辑回调函数
 * @param onDelete - 删除回调函数
 */
const TopicCard: React.FC<TopicCardProps> = ({ topic, onEdit, onDelete }) => {
	const navigator = useNavigate();
	/**
	 * 处理删除确认弹窗
	 * 阻止事件冒泡并显示删除确认弹窗
	 * @param e - 鼠标点击事件
	 */
	const handleDelete = useCallback(
		(e: React.MouseEvent) => {
			e.stopPropagation(); // 阻止事件冒泡
			Modal.confirm({
				title: '提示',
				content: '确定删除该选题吗？删除后不可恢复。',
				okText: '确定',
				cancelText: '取消',
				onOk: () => onDelete(topic.id)
			});
		},
		[topic.id, onDelete]
	);

	/**
	 * 处理编辑操作
	 * 阻止事件冒泡并调用编辑回调函数
	 * @param e - 鼠标点击事件
	 */
	const handleEdit = useCallback(
		(e: React.MouseEvent) => {
			e.stopPropagation(); // 阻止事件冒泡
			onEdit(topic);
		},
		[topic, onEdit]
	);

	// 处理点击事件
	const handleClick = useCallback(() => {
		navigator(`/my-research/detail?id=${topic.id}`);
	}, [topic, navigator]);

	return (
		<Card
			className="w-350 mb-4 shadow-sm hover:shadow-md transition-shadow border border-gray-200"
			onClick={handleClick}
			actions={[
				<div
					key="edit"
					className="flex items-center justify-center h-12 min-h-12 cursor-pointer"
					onClick={handleEdit}>
					<EditOutlined className="text-18 text-blue-500 hover:text-blue-700" />
				</div>,
				<div
					key="delete"
					className="flex items-center justify-center h-12 min-h-12 cursor-pointer"
					onClick={handleDelete}>
					<DeleteOutlined className="text-18 text-red-500 hover:text-red-700" />
				</div>
			]}>
			<div>
				<h3 className="text-16 font-medium text-gray-800 m-b-15 line-clamp-2">{topic.name}</h3>
				<div className="h-80 overflow-auto">
					<div className="flex flex-wrap gap-4">{topic.tags}</div>
				</div>
			</div>
		</Card>
	);
};

/**
 * 选题列表组件
 * 展示选题卡片列表和分页器
 */
interface TopicListProps {
	topicList: ITopicInfoResponse[];
	total: number;
	pagination: ITopicListParams;
	loading: boolean;
	onEdit: (topic: ITopicInfoResponse) => void;
	onDelete: (id: string) => void;
	onPaginationChange: (pageNum: number, pageSize: number) => void;
	onAddTopic: () => void;
}

const TopicList: React.FC<TopicListProps> = ({
	topicList,
	total,
	pagination,
	onEdit,
	onDelete,
	onPaginationChange,
	onAddTopic
}) => {
	return (
		<div className="p-6">
			<div className="flex justify-start items-center mb-6">
				<Button type="primary" className="m-b-15" icon={<PlusOutlined />} onClick={onAddTopic}>
					添加选题
				</Button>
			</div>

			<div className="min-h-300">
				<div className="flex flex-wrap gap-15">
					{topicList.map(topic => (
						<TopicCard key={topic.id} topic={topic} onEdit={onEdit} onDelete={onDelete} />
					))}
				</div>
			</div>

			{total > 0 && (
				<AppPagination
					current={pagination.pageNum}
					pageSize={pagination.pageSize}
					total={total}
					onChange={onPaginationChange}
				/>
			)}
		</div>
	);
};

// ==================== 主组件 ====================

/**
 * 研究选题主组件
 * 管理研究选题的展示、新增、编辑、删除功能
 * 支持分页和空状态展示
 */
const ResearchTopics: React.FC = () => {
	const { state, loading, actions } = useTopicManagement();

	const { topicList, total, pagination, isModalVisible, currentEditTopic } = state;

	const {
		handleDeleteTopic,
		handleSaveTopic,
		handleEditTopic,
		handleAddTopic,
		handleCloseModal,
		handlePaginationChange
	} = actions;

	/**
	 * 判断是否显示空状态
	 */
	const shouldShowEmptyState = useMemo(() => {
		return !loading && topicList.length === 0 && pagination.pageNum === 1;
	}, [loading, topicList.length, pagination.pageNum]);

	// 渲染空状态
	if (shouldShowEmptyState) {
		return (
			<>
				<EmptyState
					className="mt-80"
					btnText="添加选题"
					description="尊敬的学者，欢迎添加您的研究选题，开启高效探索之旅。"
					onCreate={handleAddTopic}
				/>
				<CreateTopicModal
					visible={isModalVisible}
					onCancel={handleCloseModal}
					onOk={handleSaveTopic}
					initialValues={currentEditTopic}
				/>
			</>
		);
	}

	// 渲染选题列表
	return (
		<>
			{!loading && (
				<TopicList
					topicList={topicList}
					total={total}
					pagination={pagination}
					loading={loading}
					onEdit={handleEditTopic}
					onDelete={handleDeleteTopic}
					onPaginationChange={handlePaginationChange}
					onAddTopic={handleAddTopic}
				/>
			)}
			<CreateTopicModal
				visible={isModalVisible}
				onCancel={handleCloseModal}
				onOk={handleSaveTopic}
				initialValues={currentEditTopic}
			/>
		</>
	);
};

export default ResearchTopics;
